<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Cache;

// 错误
function json_err( $error_code = null, $modify_msg = [] ){
    if( empty($error_code) ){ echo '状态编号不能为空！'; exit();}
    $err_msg =  require_once($_SERVER['DOCUMENT_ROOT']."../../application/error/index.php");
    if (count($err_msg) != count(array_unique($err_msg))) { echo '错误提示文件存在重复，请检查！'; exit(); }
    if( !isset($err_msg[$error_code]) ){ echo "<strong style='color: red'>${error_code}</strong>编号，错误文件未找到，请前往添加对应状态！"; exit(); }
    // 是否存在修改提示
    $len = substr_count($err_msg[$error_code], '{@}'); // 获取占位符个数
    if($len > 0){
        // 填充
        $arrn= array_fill(0, $len, '{@}');

        // 替换占位符
        $text_msg =  str_replace($arrn, $modify_msg, $err_msg[$error_code], $i);
        error_results($error_code, $text_msg);
    }
    error_results($error_code, $err_msg[$error_code]);
}

// 返回错误提示
function error_results($code = 0, $message = '')
{
    $ret['code'] = $code;
    if ($message !== '') {
        $ret['msg'] = $message;
    }

    echo json_encode($ret);
    exit;
}

// 对象转数组
function obj_to_arr($obj)
{
    return json_decode(json_encode($obj), true);
}

// 返回消息提示
function _action_result($code = 0, $data = [] ,$message = '')
{
    $ret['code'] = $code;
    if ($message !== '') {
        $ret['msg'] = $message;
    }
    $ret['data'] = $data;
    echo json_encode($ret);
    exit;
}

/**
 *
 * 产生随机字符串，不长于32位
 * @param int $length
 * @return 产生的随机字符串
 */
function getNonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}



/**
 * 导出excel
 *
 * @param array $data   导出的数据集
 * @param string $fileName  导出的文件名
 * @param array $title  导出的标题行,如果为空则从数据集中获取
 * @param boolean $width   是否设置自动宽度
 * @param boolean $center   是否设置居中
 * @return void
 */
function exportExcel($data = [], $fileName = '', $title = [], $width = false, $start = '', $end = '', $center = true, $isDown = false, $savePath = './runtime/')
{
    import('office.phpexcel.Classes.PHPExcel', VENDOR_PATH, '.php');

    $objPHPExcel = new PHPExcel();
    ini_set("memory_limit", "1024M");
    set_time_limit(0);
    $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
    if (!\PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
        die($cacheMethod . " 缓存方法不可用" . EOL);
    }

    //横向单元格标识
    // $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', '');

    $objSheet = $objPHPExcel->getActiveSheet(0);
    $objSheet->setTitle($fileName); //设置sheet名称
    //填写数据
    if ($data) {
        $_row = 1; //设置纵向单元格标识
        if (empty($title)) {
            $title = array_keys($data[0]);
        }
        $_cnt = count($title);
        $cellName = getCellName($_cnt);
        $objSheet->mergeCells('A' . $_row . ':' . $cellName[$_cnt - 1] . $_row); //合并单元格
        if (!empty($start) && !empty($end)) {
            $objSheet->setCellValue('A' . $_row, '导出时间：' . $start. '-'. $end); //设置合并后的单元格内容
        } else {
            $objSheet->setCellValue('A' . $_row, '导出时间：' . date("Y-m-d")); //设置合并后的单元格内容
        }
        $_row++;
        $i = 0;

        foreach ($title as $name) { //设置列标题
            $objSheet->setCellValue($cellName[$i] . $_row, $name);
            if ($width) {
                $objSheet->getColumnDimension($cellName[$i])->setWidth(mb_strlen($name) * intval($width)); //设置单元格宽度
            } else {
                $objSheet->getColumnDimension($cellName[$i])->setAutoSize(true); //自动大小
            }
            $objSheet->getStyle($cellName[$i] . $_row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //居中
            $i++;
        }
        $_row++;
        $objSheet->freezePane('A' . $_row); //冻结首行

        $i = 0;
        foreach ($data as $_v) {
            $j = 0;
            foreach ($_v as $k => $_cell) {
                $_cell = $_cell ?? '';
                $type = PHPExcel_Cell_DataType::TYPE_STRING; //字符串型
                if (gettype($_cell) !== 'string') {
                    $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; //数值型
                } else {
                    if ($center) {
                        $objSheet->getStyle($cellName[$j] . ($i + $_row))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //居中
                    }
                }
                $objSheet->setCellValueExplicit($cellName[$j] . ($i + $_row), $_cell, $type);
                $j++;
            }
            $i++;
        }
    }

    $objPHPExcelWrite = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    //文件名处理
    if (!$fileName) {
        $fileName = uniqid(time(), true);
    }
    if ($isDown) { //网页下载
        $savePath = rtrim($savePath, '/');
        $_savePath = $savePath . '/' . $fileName . '.xlsx';
        $objPHPExcelWrite->save($_savePath);

        return $_savePath;
    }
    $_fileName = iconv("utf-8", "gb2312", $fileName); //转码


    header('pragma:public');
    header("Content-Disposition:attachment;filename=$_fileName.xlsx");
    header("Content-Type: application/vnd.ms-excel; charset==UTF-8");
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Cache-Control: max-age=0');
    $objPHPExcelWrite->save('php://output');exit;

}
/**
 * 根据表格列数获取excel列标识符
 *
 * @param int $count 当前excel需要的列数
 * @return array
 */
function getCellName(int $count): array
{
    $alphabet = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    $arr = [];
    // $size = ceil($count/26);
    $size = 0;
    $ii = 1;
    for ($i = 0; $i < $count; $i++) {
        if ($ii == 27) {
            $ii = 1;
            $size++;
        }
        $arr[] = $alphabet[$size] . $alphabet[$ii];
        $ii++;
    }
    return $arr;
}

/**
 * 生成不重复的随机数字(不能超过10位数，否则while循环陷入死循环)
 * @param  int $start 需要生成的数字开始范围
 * @param  int $end 结束范围
 * @param  int $length 需要生成的随机数个数
 * @return number      生成的随机数
 */
function getRandNumber($start = 0, $end = 9, $length = 8)
{
    //初始化变量为0
    $count = 0;
    //建一个新数组
    $temp = array();
    while ($count < $length) {
        //在一定范围内随机生成一个数放入数组中
        $temp[] = mt_rand($start, $end);
        //$data = array_unique($temp);
        //去除数组中的重复值用了“翻翻法”，就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
        $data = array_flip(array_flip($temp));
        //将数组的数量存入变量count中
        $count = count($data);
    }
    //为数组赋予新的键名
    shuffle($data);
    //数组转字符串
    $str = implode(",", $data);
    //替换掉逗号
    $number = str_replace(',', '', $str);
    return $number;
}

//随机生成不重复的8位卡密
function makeCardPassword()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    ) ;
    return $d;
}
    // 请求【get】
    function https_request($url,$data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    /**
    * joker
    *  CURL请求 / 发送HTTP请求
    * @param $url string 请求url地址
    * @param $method string 请求方法 get post
    * @param null $postfields post数据数组
    * @param array $headers 请求header信息
    * @param bool|false $debug  调试开启 默认false
    * @return mixed
    */

    function send_request($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {

        $method = strtoupper($method);

        $ci = curl_init();

        /* Curl settings */

        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");

        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */

        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */

        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {

            case "POST":

                curl_setopt($ci, CURLOPT_POST, true);

                if (!empty($postfields)) {

                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;

                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);

                }

                break;

            default:

                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */

                break;

        }

        $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;

        curl_setopt($ci, CURLOPT_URL, $url);

        if($ssl){

            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts

            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在

        }

        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/

        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {

            curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);

        }

        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/

        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */

        $response = curl_exec($ci);

        $requestinfo = curl_getinfo($ci);

        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if ($debug) {

            echo "=====post data======\r\n";

            var_dump($postfields);

            echo "=====info===== \r\n";

            print_r($requestinfo);

            echo "=====response=====\r\n";

            print_r($response);

        }

        curl_close($ci);

        return $response;

        //return array($http_code, $response,$requestinfo);

    }


//验证省份证格式是否正确
function isIdno($id){
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if(!preg_match($regx, $id)){
        return false;
    }
    if(15==strlen($id)){//检查15位
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth)) {
            return false;
        }else{
            return true;
        }
    }else{//检查18位
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth)){//检查生日日期是否正确
            return false;
        }else{
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ( $i = 0; $i < 17; $i++ ) {
                $b = (int) $id{$i};
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id,17, 1)) {
                return false;
            }else{
                return true;
            }
        }
    }
}

function curlPost($url, $data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if(!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;

}


